import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/register.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/models/register/paymentRecordDto.dart';
import 'package:ichinesereader/models/register/priceResult.dart';
import 'package:ichinesereader/pages/register/school/billingForSchool.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:get/get.dart';

import '../../../constants.dart';
import '../../../themes/appTheme.dart';

// ignore: must_be_immutable
class SchoolRegister extends StatefulWidget {
  SchoolRegister({
    Key? key,
  }) : super(key: key);

  @override
  State<SchoolRegister> createState() => _SchoolRegisterState();
}

class _SchoolRegisterState extends State<SchoolRegister> {
  int _currentStep = 0;
  var box = Hive.box('appconfig');
  final RegisterController _registerController = new RegisterController();
  final SchoolRegisterFormStep1 formModel1 = new SchoolRegisterFormStep1();
  final SchoolRegisterFormStep2 formModel2 = new SchoolRegisterFormStep2();
  late FormGroup form1;
  late FormGroup form2;
  TextEditingController _textController1 = new TextEditingController();
  TextEditingController _textController2 = new TextEditingController();

  PriceData _priceData = new PriceData();

  void _onSubmit() async {
    if (!form1.valid || !form2.valid) {
      form1.markAllAsTouched();
      form2.markAllAsTouched();
      return;
    }
    try {
      PaymentRecordDto dto = new PaymentRecordDto();
      dto.studentNumber = this.form1.control('studentNumber').value;
      dto.paymentTerm = this.form1.control('paymentTerm').value;
      dto.zipCode = this.form1.control('zipCode').value;
      dto.schoolName = this.form2.control('schoolName').value;
      dto.firstName = this.form2.control('firstName').value;
      dto.lastName = this.form2.control('lastName').value;
      dto.email = this.form2.control('email').value;
      dto.phone = this.form2.control('phone').value;
      dto.paymentItem = 'school';
      dto.platform = 'reader';
      dto.subtotalPrice = _priceData.subtotalPrice.toString();
      dto.tax = _priceData.tax.toString();
      dto.unitPrice = _priceData.unitPrice.toString();
      // var id = "61bde6e4-417e-4694-8ad8-413831d60e01";
      // var quoteNumber = "2304282088";
      // Get.to(() => BillingForSchool(id: id, quoteNumber: quoteNumber));
      _registerController.createPaymentRecord(dto).then((res) {
        if (res.id.isNotEmpty) {
          Get.snackbar('Message'.tr, 'Successfully create a quote'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
          //id 61bde6e4-417e-4694-8ad8-413831d60e01
          //quoteNumber 2304282088
          Get.to(
              () => BillingForSchool(id: res.id, quoteNumber: res.quoteNumber));
        } else {
          Get.snackbar('Message'.tr, 'Failed to get a quote.'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
        }
      });
    } catch (error) {
      Get.snackbar('Message'.tr, 'Failed to get a quote.'.tr,
          backgroundColor: Theme.of(context).primaryColor,
          colorText: Theme.of(context).primaryColorLight,
          snackPosition: SnackPosition.BOTTOM);
      Log.debug(error);
    }
  }

  cancel() {
    if (_currentStep > 0) setState(() => _currentStep -= 1);
  }

  continued() {
    if (_currentStep == 0) {
      if (!form1.valid) {
        form1.markAllAsTouched();
        return;
      }
    }
    if (_currentStep == 1) {
      if (!form2.valid) {
        form2.markAllAsTouched();
        return;
      }
    }
    if (_currentStep == 2) {
      if (this.formModel1.form.valid && this.formModel2.form.valid)
        _onSubmit();
      else {
        this.formModel1.form.markAllAsTouched();
        this.formModel2.form.markAllAsTouched();
      }
    }
    if (_currentStep < 2) setState(() => _currentStep += 1);
  }

  tapped(int step) {
    setState(() => _currentStep = step);
  }

  @override
  void initState() {
    form1 = formModel1.form;
    form2 = formModel2.form;
    form1.control('studentNumber').value = 0;
    form1.control('paymentTerm').value = 1;
    form1.control('zipCode').value = '';
    form2.control('schoolName').value = '';
    form2.control('firstName').value = '';
    form2.control('lastName').value = '';
    form2.control('email').value = '';
    form2.control('phone').value = '';
    form2.control("email").setAsyncValidators([mustUniqueEmail]);
    _textController1.text = "0";
    _textController2.text = "0";

    super.initState();
  }

  calculatePrice() async {
    var studentNumber = form1.control('studentNumber').value;
    var paymentTerm = form1.control('paymentTerm').value;
    var zipCode = form1.control('zipCode').value;
    _registerController
        .calculatePrice(studentNumber, paymentTerm, zipCode)
        .then((res) {
      _textController1.text = res.subtotalPrice ?? "";
      _textController2.text = res.unitPrice ?? "";
      setState(() {
        _priceData = res;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build school register stepper');
    FormGroup form1 = formModel1.form;

    _buildForm1() {
      List<Widget> formWidget = [];
      formWidget.add(ReactiveTextField(
        formControlName: 'studentNumber',
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'No. of Student'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
        onChanged: (control) {
          form1.control('studentNumber').value = control.value;
          if (form1.valid) {
            calculatePrice();
          }
        },
      ));

      formWidget.add(
        ReactiveDropdownField<dynamic>(
          dropdownColor: Get.isDarkMode
              ? AppTheme.colors.darkTheme2
              : Get.theme.primaryColor,
          formControlName: 'paymentTerm',
          decoration: InputDecoration(
              labelText: 'Choose Duration'.tr,
              labelStyle: TextStyle(
                  color: Get.isDarkMode ? Colors.white : Colors.black)),
          onChanged: (value) {
            form1.control('paymentTerm').value = value.value;
            if (form1.valid) {
              calculatePrice();
            }
          },
          items: Constants.termOptions.map((value) {
            return DropdownMenuItem(
              value: value.value,
              child: Text(
                value.label.toString(),
                style: Theme.of(context).textTheme.titleSmall?.copyWith(
                    color: Get.isDarkMode ? Colors.white : Colors.black),
                overflow: TextOverflow.fade,
              ),
            );
          }).toList(),
        ),
      );

      formWidget.add(ReactiveTextField(
        formControlName: 'zipCode',
        style: TextStyle(
            fontFamily: 'Montserrat',
            fontSize: 15.0,
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        onChanged: (control) {
          form1.control('zipCode').value = control.value;
          if (form1.valid) {
            calculatePrice();
          }
        },
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'Zip Code'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));

      formWidget.add(SizedBox(
        height: 20,
      ));
      formWidget.add(TextField(
        readOnly: true,
        controller: _textController1,
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          alignLabelWithHint: true,
          prefixIcon: Text("\$"),
          labelText: 'Subtotal Price'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));
      formWidget.add(TextField(
        readOnly: true,
        controller: _textController2,
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          alignLabelWithHint: true,
          labelText: 'Unit Price'.tr,
          prefixIcon: Text("\$"),
          suffixText: "student/yr".tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));
      return formWidget;
    }

    _buildForm2() {
      List<Widget> formWidget = [];

      formWidget.add(ReactiveTextField(
        formControlName: 'schoolName',
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'School Name'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));
      formWidget.add(ReactiveTextField(
        formControlName: 'firstName',
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'First Name'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));
      formWidget.add(ReactiveTextField(
        formControlName: 'lastName',
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'Last Name'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));
      formWidget.add(ReactiveTextField(
        formControlName: 'email',
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        validationMessages: {
          'unique': (_) => 'The email is already used'.tr,
        },
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'Email'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));
      formWidget.add(ReactiveTextField(
        formControlName: 'confirmemail',
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        validationMessages: {
          ValidationMessage.mustMatch: (_) => 'Confirm email mismatch!'.tr,
        },
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'Confirm Email'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));

      formWidget.add(ReactiveTextField(
        formControlName: 'phone',
        style: TextStyle(
            fontSize: 15.0,
            fontFamily: 'Montserrat',
            color: Get.isDarkMode ? Colors.white : Colors.black),
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          labelText: 'Phone'.tr,
          labelStyle: TextStyle(
              fontFamily: 'Montserrat',
              color:
                  Get.isDarkMode ? Get.theme.primaryColorLight : Colors.black),
        ),
      ));

      return formWidget;
    }

    _buildTable() {
      var tableHeaders = [
        Container(
            child: Text('No. of Students Accounts'),
            padding: EdgeInsets.all(10)),
        Container(child: Text('Duration(Years)'), padding: EdgeInsets.all(10)),
        Container(child: Text('Unit Price(USD)'), padding: EdgeInsets.all(10)),
        Container(
            child: Text('Subtotal Price(USD)'), padding: EdgeInsets.all(10)),
      ];

      return Table(
          border: TableBorder.all(),
          columnWidths: const <int, TableColumnWidth>{
            0: IntrinsicColumnWidth(),
            1: FlexColumnWidth(),
            2: FlexColumnWidth(),
            3: FlexColumnWidth(),
          },
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          children: [
            TableRow(children: tableHeaders.toList()),
            TableRow(children: [
              Container(
                  child: Text(
                      this.form1.control("studentNumber").value.toString()),
                  padding: EdgeInsets.all(10)),
              Container(
                  child:
                      Text(this.form1.control("paymentTerm").value.toString()),
                  padding: EdgeInsets.all(10)),
              Container(
                  child: Text(_priceData.unitPrice.toString()),
                  padding: EdgeInsets.all(10)),
              Container(
                  child: Text(_priceData.subtotalPrice.toString()),
                  padding: EdgeInsets.all(10))
            ])
          ]);
    }

    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
          title: Text('Easily finish your order by following 3 steps!'),
          leading: BackButton(onPressed: () {
            Navigator.of(context).pop();
          })),
      body: Stepper(
        currentStep: _currentStep,
        physics: ScrollPhysics(),
        onStepTapped: (step) => tapped(step),
        //Customising the Stepper controls
        controlsBuilder: (BuildContext context, ControlsDetails controls) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                ElevatedButton(
                  onPressed: controls.onStepContinue!,
                  child: Text('NEXT'.tr),
                ),
                if (_currentStep != 0)
                  TextButton(
                    onPressed: controls.onStepCancel,
                    child: Text(
                      'BACK'.tr,
                      style: TextStyle(color: Color.fromARGB(255, 97, 96, 96)),
                    ),
                  ),
              ],
            ),
          );
        },
        onStepContinue: continued,
        onStepCancel: cancel,
        type: (GetPlatform.isAndroid || GetPlatform.isIOS)
            ? StepperType.vertical
            : StepperType.horizontal,
        steps: [
          Step(
            title: Text('Get A Quote'.tr),
            isActive: _currentStep >= 0,
            state: _currentStep >= 0 ? StepState.complete : StepState.disabled,
            content: Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: ReactiveForm(
                formGroup: form1,
                child: Column(
                  children: _buildForm1(),
                ),
              ),
            ),
          ),
          Step(
            title: Text('More About You'.tr),
            isActive: _currentStep >= 0,
            state: _currentStep >= 1 ? StepState.complete : StepState.disabled,
            content: Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: ReactiveForm(
                formGroup: form2,
                child: Column(
                  children: _buildForm2(),
                ),
              ),
            ),
          ),
          Step(
            title: Text('Review'.tr),
            isActive: _currentStep >= 0,
            state: _currentStep >= 2 ? StepState.complete : StepState.disabled,
            content: Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: ReactiveForm(
                formGroup: form2,
                child: Column(children: [
                  _buildTable(),
                  SizedBox(
                    height: 20,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text("Total before Tax:"),
                      Text("\$ ${_priceData.subtotalPrice}")
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text("Esimiated tax to be collectred:"),
                      Text("\$ ${_priceData.tax}")
                    ],
                  ),
                  const Divider(
                    height: 50,
                    thickness: 1,
                    indent: 0,
                    endIndent: 0,
                    color: Color.fromARGB(255, 216, 212, 212),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text("Total:"),
                      Text("\$ ${_priceData.totalPrice}")
                    ],
                  )
                ]),
              ),
            ),
          )
        ],
      ),
    );
  }
}
